package com.freestyle.seatabusiness.account.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.freestyle.seatabusiness.account.dao.AccountTblMapper;
import com.freestyle.seatabusiness.api.models.AccountTbl;
import com.freestyle.seatabusiness.api.service.AccountService;
import org.apache.dubbo.config.annotation.DubboService;

import javax.annotation.Resource;

/**
 * Created by rocklee on 2021/12/16 10:20
 */
@DubboService(cluster = "failfast") //不做任何重试
public class AccountServiceImp implements AccountService {
  @Resource
  private AccountTblMapper accountTblMapper;

  @Override
  public void debit(String userId, int money) {
    AccountTbl account=accountTblMapper.selectOne(Wrappers.lambdaQuery(AccountTbl.class)
            .eq(AccountTbl::getUserId,userId));
    if (account==null){
      throw new RuntimeException("无效帐户:"+userId);
    }
    account.setMoney(account.getMoney()-money);
    if (account.getMoney()<0){
      throw new RuntimeException("帐户余额不足:"+userId);
    }
    //accountTblMapper.updateById(account);
    //accountTblMapper.updateByPrimaryKey(account);
    accountTblMapper.updateById(account);
  }

  @Override
  public void addAccount(String userId, int money) {
    AccountTbl account=accountTblMapper.selectOne(new LambdaQueryWrapper<AccountTbl>()
            .eq(AccountTbl::getUserId,userId));
    //AccountTbl account=accountTblMapper.selectOne(new AccountTbl(userId));
    if (account!=null){
      throw new RuntimeException(String.format("帐户%s已存在",userId));
    }
    account=new AccountTbl(userId);
    account.setMoney(money);
    accountTblMapper.insert(account);
  }

}
